package Config::System::t::File;

use strict;
use warnings;
use Test::More;
use Test::Exception;
use IO::All -utf8;
use aliased 'Config::System::File';

use base 'Test::Class';

my $File = 'foo.properties';
my $Foo  = 'Foo';
my $Bam  = 'Bam';

sub eut { shift->{_eut} }

sub create_file {
    my ($self, $config) = @_;
    $config = "[$Foo]\nBar=1" if @_ == 1;
    io($File)->write($config);
    my %parsed = File->new(path => $File)->parse;
    return %parsed;
}

sub rm_file: Test(teardown) { io($File)->unlink if -e $File }

# tests ------------------------------------------------------------------------

sub no_readable_config_file: Test
    { throws_ok { File->new(path => 'non_existing')->parse } qr/non_existing/ }

sub with_readable_config_file: Test { ok File->new(path => $File) }

sub get_value: Test { is {shift->create_file}->{$Foo}->{Bar}, 1 }

sub several_sections_and_properties: Test(2) {
    my $self     = shift;
    my $config   = "[$Foo]\nBar=0\n[$Bam]\nBaz=123";
    my %sections = $self->create_file($config);
    is $sections{$Foo}->{Bar}, 0, 'section 1';
    is $sections{$Bam}->{Baz}, 123, 'section 2';
}

sub empty_section: Test {
    my $self = shift;
    dies_ok { $self->create_file("X=6") };
}

sub section_but_no_properties: Test {
    my $self = shift;
    ok !exists {$self->create_file("[$Foo]")}->{$Foo}->{Bar};
}

sub no_section_no_properties: Test {
    my $self = shift;
    my %sections = $self->create_file('');
    is scalar(keys %sections), 0;
}

sub dont_parse_twice: Test {
    my $self = shift;
    io($File)->write("[$Foo]\nBar=1");
    my $file = File->new(path => $File);
    $file->parse;
    io($File)->unlink;
    is { $file->parse }->{$Foo}->{Bar}, 1;
}

sub clone: Test {
    my $self = shift;
    io($File)->write("[$Foo]\nBar=1");
    my $file = File->new(path => $File);
    $file->parse;
    my %parsed = $file->clone->parse;
    is $parsed{$Foo}->{Bar}, 1;
}

1;
